package com.slipper.system.codeless.controller;

import com.slipper.constants.Constants;
import com.slipper.core.gson.GsonUtil;
import com.slipper.system.backup.service.BackupRestoreService;
import com.slipper.system.codeless.bo.ViewFolderBO;
import com.slipper.system.codeless.bo.ViewBO;
import com.slipper.system.codeless.service.ViewFolderService;
import com.slipper.system.codeless.service.ViewService;
import com.slipper.system.codeless.vo.ViewVO;
import com.slipper.core.tree.Node;
import com.slipper.core.tree.Tree;
import com.slipper.core.tree.TreeInfo;
import com.slipper.core.tree.TreeUtil;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 视图信息表
 */
@RestController
@RequestMapping("/system/view")
public class ViewController {
    private static final Logger logger = LoggerFactory.getLogger(ViewController.class);

    @Resource
    private ViewFolderService viewFolderService;
    @Resource
    private ViewService viewService;
    @Resource
    private BackupRestoreService backupRestoreService;
    
    @PostMapping(value = "/queryBy")
    public String queryBy(@RequestBody ViewBO bo) {
        if(Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(viewService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody ViewBO bo) {
        return ResultUtil.successResult(viewService.queryList(bo));
    }
    
    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody ViewBO bo) {
        return ResultUtil.successResult(viewService.queryPage(bo));
    }

    @PostMapping("/queryTree")
    public String queryTree() {
        List<ViewFolderBO> folderList = viewFolderService.queryList(new ViewFolderBO());
        TreeInfo folderTreeInfo = new TreeInfo("视图");
        folderTreeInfo.setRootId(Constants.ROOT_ID);
        folderTreeInfo.setIdField("id");
        folderTreeInfo.setPidField("parentId");
        folderTreeInfo.setTextField("name");
        folderTreeInfo.setNodeType("folder");
        folderTreeInfo.setSortField("ordinal");

        List<ViewBO> groovyList = viewService.queryList(new ViewBO());
        TreeInfo groovyTreeInfo = new TreeInfo("");
        groovyTreeInfo.setIdField("id");
        groovyTreeInfo.setPidField("folderId");
        groovyTreeInfo.setTextField("name");
        groovyTreeInfo.setNodeType("view");
        groovyTreeInfo.setSortField("ordinal");

        Node rootNode = TreeUtil.buildTree(
                "asc",
                new Tree(folderTreeInfo, BeanUtil.setOrdinal(folderList)),
                new Tree(groovyTreeInfo, BeanUtil.setOrdinal(groovyList, folderList.size())));
        return ResultUtil.successResult(rootNode);
    }

    @PostMapping(value = "/save")
    public String save(@RequestBody ViewBO bo) {
        if (Tool.isBlank(bo.getSqlText())) {
            return ResultUtil.failureResult("视图内容不能为空！");
        }

        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(viewService.save(bo), bo);
    }

    @PostMapping(value = "/saveSimple")
    public String saveSimple(@RequestBody ViewBO bo) {
        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(viewService.saveSimple(bo), bo);
    }

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody Map<String, Object> data) {
        String fileName = "view-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        ViewVO vo = backupRestoreService.backupView(data);
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(vo)));
    }

    @PostMapping(value = "/importData")
    public String importData(ViewBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }

        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            backupRestoreService.restoreView(AESUtil.decrypt(content));
            return ResultUtil.successResult("导入视图成功。");
        } catch (Exception e) {
            logger.error("文件解释出错！", e);
            return ResultUtil.failureResult("文件解释出错！");
        }
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody ViewBO bo) {
        return ResultUtil.successResult(viewService.delete(bo));
    }

    @PostMapping(value = "/parseView")
    public String parseView(@RequestBody ViewBO bo) {
        if (Tool.isBlank(bo.getSqlText())) {
            return ResultUtil.failureResult("视图语句不能为空！");
        }

        return viewService.parseView(bo);
    }

    @PostMapping(value = "/queryColumn")
    public String queryColumn(@RequestBody ViewBO bo) {
        if (Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("视图参数不正确！");
        }

        return viewService.queryColumn(bo);
    }
}
